<template>
  <el-dialog
    title="文字设置"
    :visible="visible"
    width="700px"
    v-dialogDrag
    :before-close="handleCancel"
  >
    <el-form
      :model="textForm"
      label-width="100px"
      size="medium"
      :rules="textRules"
      ref="textFormRef"
      inline
    >
      <div class="text-wrapper">
        <div class="text-form-items">
          <el-form-item label="X坐标" required prop="x">
            <el-input-number
              v-model="textForm.x"
              placeholder="请输入X坐标"
              :min="1"
            ></el-input-number>
          </el-form-item>

          <el-form-item label="Y坐标" required prop="y">
            <el-input-number
              v-model="textForm.y"
              placeholder="请输入Y坐标"
              :min="1"
            ></el-input-number>
          </el-form-item>

          <el-form-item label="字体大小" required prop="fontSize" style="width: 600px;">
            <el-input-number
              v-model="textForm.fontSize"
              placeholder="请输入"
              :max="40"
              :min="12"
              
            ></el-input-number>
          </el-form-item>
          <el-form-item label="文字内容" required >
            <div class="content-controls">
              <el-button type="success" size="mini" @click="handleAddText">
                <i class="el-icon-plus"></i> 加文字
              </el-button>
              <el-button type="primary" size="mini" @click="handleAddTag()">
                <i class="el-icon-price-tag"></i> 加标签
              </el-button>
            </div>

            <div class="tag-wrapper" v-if="dynamicTags.length > 0">
              <div
                v-for="(item, index) in dynamicTags"
                :key="index"
                class="tag-item"
              >
                <!-- 文字输入框 -->
                <el-input
                  v-if="item.tp === 1"
                  v-model="item.text"
                  placeholder="请输入文字"
                  size="small"
                  style="width: 300px; margin-right: 10px;"
                  @change="handleTagChange(index)"
                ></el-input>

                <!-- 标签显示 -->
                <el-tag
                  v-else-if="item.tp === 2"
                  type="info"
                  style="width: 300px; height: 32px; line-height: 32px;"
                >
                  {{ item.val || item.text }}
                </el-tag>

                <div class="tag-actions">
                  <el-tooltip
                    v-if="item.tp === 2"
                    effect="dark"
                    content="修改"
                    placement="top"
                  >
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click="handleAddTag(item, index)"
                    ></el-button>
                  </el-tooltip>

                  <el-tooltip
                    effect="dark"
                    content="删除"
                    placement="top"
                  >
                    <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      @click="handleDelTag(index)"
                    ></el-button>
                  </el-tooltip> 
                </div>
              </div>
            </div>

            <!-- 预览区域 -->
            <div v-if="dynamicTags.length > 0" class="preview-area">
              <div class="preview-label">预览效果：</div>
              <div
                class="preview-content"
                :style="{
                  fontSize: textForm.fontSize + 'px',
                  color: textForm.color || '#000000',
                  fontFamily: textForm.fontFamily
                }"
              >
                {{ previewText }}
              </div>
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>

    <div class="btnGroup">
      <el-button
        @click="handleCancel"
        size="small"
        icon="el-icon-circle-close"
      >
        取消
      </el-button>
      <el-button
        type="primary"
        @click="handleSave"
        size="small"
        icon="el-icon-circle-check"
      >
        确定
      </el-button>
    </div>

    <tagSet :stationId="stationId" :visible="tagSettingDialog" :tagSettingData="tagSettingData" @handleSaveEditTag="handleSaveEditTag" @handleCloseDialog="handleCloseTag" isIndicator :modal="false"/>
  </el-dialog>
</template>

<script>
import{getLableByID,EditPointInfoCompSet,saveR_Lable} from '@/api/https'
import tagSet from '@/components/base/tagSet.vue';
export default {
  name: 'TextDialog',
  components:{tagSet},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    textForm: {
      type: Object,
      default: () => ({
        x: 0,
        y: 0,
        fontSize: 14,
        color: '#000000',
        fontFamily: ''
      })
    },
    stationId: {
      type: [String, Number],
      default: ''
    },
    dynamicTags:{
      type: Array,
      default: ()=>{
        return []
      }
    }
  },
  data() {
    return {
      textRules: {
        x: [
          { required: true, message: '请输入X坐标', trigger: 'blur' }
        ],
        y: [
          { required: true, message: '请输入Y坐标', trigger: 'blur' }
        ],
        fontSize: [
          { required: true, message: '请输入字体大小', trigger: 'blur' }
        ]
      },
      tagSettingData:{},
      tagSettingDialog:false,
      editTagIndex:''
    }
  },
  computed: {
    previewText() {
      let result = ''
      this.dynamicTags.forEach(item => {
        if (item.tp === 1) {
          result += item.text || ''
        } else if (item.tp === 2) {
          result += `[${item.val || item.text}]`
        }
      })
      return result
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.resetFormValidation()
          })
        }
      }
    }
  },
  methods: {
    resetFormValidation() {
      if (this.$refs.textFormRef) {
        this.$refs.textFormRef.clearValidate()
      }
    },

    handleCancel() {
      this.resetFormValidation()
      this.$emit('cancel')
    },

    handleSave() {
      this.$refs.textFormRef.validate((valid) => {
        if (valid) {
          if (this.dynamicTags.length === 0) {
            this.$message.error('请至少添加一个文字或标签')
            return false
          }
          
          // 检查所有文字输入框是否为空
          const hasEmptyText = this.dynamicTags.some(item => 
            item.tp === 1 && (!item.text || item.text.trim() === '')
          )
          
          if (hasEmptyText) {
            this.$message.error('文字内容不能为空')
            return false
          }
          this.$emit('save', {
            ...this.textForm,
            dynamicTags: [...this.dynamicTags]
          },this.previewText)
        } else {
          return false
        }
      })
    },

    handleAddText(){
      this.dynamicTags.push({
          tp:1,
          text:'',
          val:''
      })
    },
    handleAddTag(data,index){
      if(data){
          this.editTagIndex = index
          getLableByID({
              LableID:data.text
          }).then(res=>{
              if(res.isSuccess){
                  this.tagSettingData = {...res.data}
                  this.tagSettingData.points = res.data.points || []
                  this.tagSettingDialog = true
              }
          })
      }else{
          this.editTagIndex = ''
          this.tagSettingData = {
              l_TP:1,
              dtPart:[],
              points:[],
              tp:3
          }
          this.tagSettingDialog = true
      }
           
    },
    handleDelTag(index){
        this.dynamicTags.splice(index,1)
    },
    handleSaveEditTag(data,codeId){
      if(this.editTagIndex !== ''){
          const _data = {
              id:data.id,
              name:data.name,
              tp:data.tp,
              field:data.tp == 1 || data.tp == 4 ? data.field : '',
              COMP:data.tp == 2 || data.tp == 6 ? data.COMP : '',
              ValueTypeID:data.ValueTypeID,
              ValueTypeNAME:data.ValueTypeNAME,
              DtModeID:data.DtModeID || 0,
              dT1:data.l_TP == 1 || data.tp == 4 ? '' :  data.dT1 || '',
              dT2:data.l_TP == 1 || data.tp == 4 ? this.e_Time || '' :  data.dT2 || '',
              reprotID:data.reprotID || 4,
              points:data.points,
              reprotTP:data.ReprotTP || 4,
              l_TP:data.l_TP,
              text:'',
              CODE_ID:codeId,
              dtPart:data.dtPart
          }
          EditPointInfoCompSet(_data).then(res=>{
              if(res.isSuccess){
                  if(res.data && res.data.text){
                      const _data = list[this.editTagIndex]
                      _data.tp = 2
                      _data.text = res.data.id
                      _data.val = res.data.text
                      this.handleCloseTag()
                  } else{
                      this.$message.error('暂无标签值，无法添加！')
                  } 
              }else{
                  this.$message.error(res.errorMessage)
              }
          })
      }else{
          const _data = {
              id:0,
              name:'',
              field:data.tp == 1 || data.tp == 4 ? data.field : '',
              COMP:data.tp == 2 || data.tp == 5 ||data.tp == 6 ? data.COMP : '',
              ValueTypeID:data.ValueTypeID,
              ValueTypeNAME:data.ValueTypeNAME,
              dT1:data.l_TP == 1 || data.tp == 4 ? '' :  data.dT1 || '',
              dT2:data.l_TP == 1 || data.tp == 4 ? '' :  data.dT2 || '',
              reprotID:4,
              reprotTP:4,
              l_TP:data.l_TP,
              tp:data.tp,
              DtModeID:data.DtModeID || 0,
              text:data.text,
              CODE_ID:codeId,
              dtPart:data.dtPart,
          }
          saveR_Lable(_data).then(res=>{
              if(res.isSuccess){
                  if(res.data && res.data.text){
                      this.dynamicTags.push({
                          tp:2,
                          text:res.data.id,
                          val:res.data.text
                      })
                      this.handleCloseTag()
                  } else{
                      this.$message.error('暂无标签值，无法添加！')
                  } 
              }else{
                  this.$message.error(res.errorMessage)
              }
          })
      }
    },
    handleCloseTag(){
      this.tagSettingDialog = false
      this.editTagIndex = ''
      this.tagSettingData = {}
    },
  }
}
</script>

<style scoped lang="scss">
.text-wrapper {
  .text-form-items {
    max-height: 550px;
    overflow-y: auto;
    padding-right: 10px;
    
    ::v-deep .el-form-item {
      margin-bottom: 16px;
    }
  }
}

.content-controls {
  margin-bottom: 15px;
  
  .el-button {
    margin-right: 10px;
  }
}

.tag-wrapper {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 15px;
}

.tag-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 5px;
  border-radius: 4px;
  background: #f8f9fa;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &:hover {
    background: #e9ecef;
  }
}

.tag-actions {
  display: flex;
  gap: 5px;
  margin-left: 10px;
  
  .el-button {
    padding: 5px;
    margin-left: 5px;
  }
}

.preview-area {
  margin-top: 15px;
  padding: 0 15px 15px 15px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  background: #fafafa;
}

.preview-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.preview-content {
  min-height: 40px;
  padding: 10px;
  background: white;
  border: 1px solid #e6e8eb;
  border-radius: 4px;
  word-break: break-all;
}

.btnGroup {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>